package com.example.learnspring.service;

import com.example.learnspring.entity.Emp;
import com.example.learnspring.entity.EmpExpr;
import com.example.learnspring.entity.EmpParam;
import com.example.learnspring.entity.Pager;
import com.example.learnspring.mapper.EmpExpMapper;
import com.example.learnspring.mapper.EmpMapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.beans.Transient;
import java.time.LocalDateTime;
import java.util.Collection;
import java.util.Collections;
import java.util.List;

@Service
public class EmpServiceImpl implements EmpService {
    @Autowired
    private EmpMapper empMapper;
    @Autowired
    private EmpExpMapper empExpMapper;
    @Override
    public Pager page(EmpParam empParam) {

        PageHelper.startPage(empParam.getPageNum(), empParam.getPageSize());
        List<Emp> emps = empMapper.empList(empParam);
        Page page = (Page) emps;
        return new Pager(page.getTotal(), page.getResult());
    }

    @Transactional
    @Override
    public boolean save(Emp emp) {
        emp.setCreateTime(LocalDateTime.now());
        emp.setUpdateTime(LocalDateTime.now());

        // 保存员工
        empMapper.saveEmp(emp);

        List<EmpExpr> list =  emp.getExpList();

        if(!CollectionUtils.isEmpty(list)){
            list.forEach(empExpr -> empExpr.setEmpId(emp.getId()));
        }
        // 保存员工工作经历
        empExpMapper.batchInsert(list);

        return false;
    }

    @Override
    public Emp getEmpById(Integer id) {

        // 连表查询
        Emp emp = empMapper.getSelectById(id);

        return emp;
    }

}
